import React from 'react';

import { Table, Typography, Popconfirm, Input, Form, Space, message, Modal, Button, DatePicker, Popover, Spin } from 'antd';
import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
//import { useLocation,useNavigate } from 'react-router-dom';
import { useGetdatamileagecheckpropsQuery, usePostadddatamileagecheckpropsMutation, usePuteditdatamileagecheckpropsMutation, usePostdatamileagecheckexcuteMutation, useDeletdatamileagecheckpropsMutation } from '../../store/request/dataworksrequests/datamileagecheckpropsrequest';
import { ExclamationCircleOutlined } from '@ant-design/icons';


// const { RangePicker } = DatePicker;
const { confirm } = Modal;

const DataMileageCheckProp = () => {

  const popovercontent = (
    <div>
      <p>执行里程校验，确保参数已选择</p>

    </div>
  );
  const loginstate = useSelector(state => state.loginpara);//loginpara={isLogined,role:{key,loginname,authoritykey,avatarpath}}
  const [paraisselected, setparaisselected] = useState(false);//用于判断是否有选中行以此来空值执行按钮的生效
  const [selectpara, setselectpara] = useState("");//设置选中行的异常值并存储进state
  const [loading, setloading] = useState(false);
  const [dateselected, setdateselected] = useState(false);//用于判断是否选择了日期执行按钮的生效

  const [selectnewrow, setselectnewrow] = useState({});//设置选中行的异常值并存储进state
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);//设置表格里的是否选中异常值


  const [isModalOpen, setIsModalOpen] = useState(false);//导入结果信息的对话框
  const [Modalinfo, setModalinfo] = useState([]);//导入结果信息
  const handleOk = () => {
    setIsModalOpen(false);
  };
  const handleCancel = () => {
    setIsModalOpen(false);
  };

  //选中时选取异常值
  const handleSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setparaisselected(true); // 执行按钮可以使用
    setselectpara(selectedRows[0]); // 把选中行的异常值存储到state中

  };
  const rowSelection = {
    type: "radio",
    selectedRowKeys,
    onChange: handleSelectChange,
  };

  const [messageApi, contextHolder] = message.useMessage();
  const [tableParams, setTableParams] = useState({
    pagination: {
      current: 1,
      pageSize: 10,
    },
  });
  const getRandomuserParams = (params) => ({
    pagesize: params.pagination?.pageSize,
    page: params.pagination?.current,
    loginname: loginstate.role.loginname
    //...params,
  });
  const [editingKey, setEditingKey] = useState(''); // 初始化正在编辑的 key 的 state
  //用于是否打开添加modal的表单页面
  const [open, setOpen] = useState(false);

  // const [badgestatus, setbadgestatus] = useState([]);

  //tableParams发生变化就会执行发送请求和参数
  const result = useGetdatamileagecheckpropsQuery(getRandomuserParams(tableParams));
  const [excutetrigger] = usePostdatamileagecheckexcuteMutation();
  const [edittrigger] = usePuteditdatamileagecheckpropsMutation();
  const [deltrigger] = useDeletdatamileagecheckpropsMutation();
  const [addtrigger] = usePostadddatamileagecheckpropsMutation();


  const [form] = Form.useForm(); // 从 Form.useForm() 中解构 form
  const isEditing = (record) => record.key === editingKey; // 定义 isEditing 函数以检查记录是否正在被编辑

  //dateString:['2024-02-01', '2024-02-08']
  const dateselect = (date, dateString) => {
    if (date === null) {
      setdateselected(false);//标识没选择日期
    }
    else {

      if (dateString.length === 2) {
        setdateselected(true);//标识选择了日期
        const newrow = { ...selectpara, startdate: dateString[0], enddate: dateString[1] };
        setselectnewrow(newrow);
        //console.log(newrow);
      }

    }

  };

  //执行导入
  const mileagecheckexcute = async () => {

    setloading(true);

    const r = await excutetrigger(selectnewrow);
    // console.log(r.data);
    // messageinfo(r);
    setModalinfo(r.data);
    setIsModalOpen(true);

    setloading(false);

  };

  // 定义 edit 函数以将 editingKey state 设置为记录的 key
  //表单更新异常值只能用setFieldsValue方法，不能用setstate方法，这样就能获取原始值
  const edit = (record) => {

    form.setFieldsValue({

      key: record.key,
      loginname: record.loginname,
      originaldatapath: record.originaldatapath,
      spdchanname: record.spdchanname,
      odochanname: record.odochanname,

      //...record,  //一展开record，就会报错date.locale is not a function，但是之前arriveddate已经赋值为空字符串，所以除了arriveddate为空外，其余属性按照record展开
    });

    setEditingKey(record.key);
  };

  const messageinfo = (editordel) => {
    //message.success('This is a success message');
    messageApi.open({
      type: 'info',
      content: editordel,
    });
    //console.log("消息框");
  };
  const messageerror = (editordel) => {
    //message.success('This is a success message');
    messageApi.open({
      type: 'error',
      content: editordel,
    });
    //console.log("消息框");
  };
  const messagesucess = (editordel) => {
    messageApi.open({
      type: 'info',
      content: editordel,
    });
  };
  //添加异常值的表单页面
  const CollectionCreateForm = ({ open, onCreate, onCancel }) => {
    const [form] = Form.useForm();
    return (
      <Modal
        open={open}
        title="添加里程校验记录"
        maskClosable={false} 
        okText="添加"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              //console.log('validateFields:', values);
              onCreate(values);
            })
            .catch((info) => {
              console.log('Validate Failed:', info);
            });
        }}
      >
        <Form
          form={form}
          layout="vertical"
          name="form_in_modal"
          initialValues={{
            modifier: 'public',
          }}
        >



          <Form.Item
            name="originaldatapath"
            label="导入路径"
            placeholder="请填写路径"
            rules={[
              {
                required: true,
                message: '请输入路径!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="spdchanname"
            label="速度列名"
            placeholder="请填写速度列名"
            rules={[
              {
                required: true,
                message: '请输入速度列名!',
              },
            ]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            name="odochanname"
            label="ODO列名"
            placeholder="请填写ODO列名"
            rules={[
              {
                required: true,
                message: '请输入ODO列名!',
              },
            ]}
          >
            <Input />
          </Form.Item>


        </Form>
      </Modal>
    );
  };

  //这个方法页面加载时就会不停的执行
  const EditableCell = ({ editing, dataIndex, title, inputType, record, index, children, ...restProps }) => { // 定义 EditableCell 组件并传入 props

    return (
      <td {...restProps}>
        {editing ? ( // 如果正在编辑，渲染带有相应 props 的 inputNode
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `请输入${title}!`,
              },
            ]}
          >
            <Input />
          </Form.Item>
        ) : (
          children // 否则渲染 children（文本）
        )}
      </td>
    );
  };
  const columns = [
    {
      title: '序号',
      dataIndex: 'key',
      editable: false,

      //render: (name) => `${name.first} ${name.last}`,
    },

    {
      title: '路径',
      dataIndex: 'originaldatapath',
      editable: true,

    },

    {
      title: '速度列名',
      dataIndex: 'spdchanname',
      editable: true,

    },
    {
      title: 'ODO列名',
      dataIndex: 'odochanname',
      editable: true,

    },
    {
      //表格最后的操作按钮
      title: '操作',
      dataIndex: 'action',
      width: '8%',
      fixed: 'right',
      render: (_, record) => { // 使用 Popconfirm 组件渲染操作列
        const editable = isEditing(record);//判断这一行的key是否为editingKey，如果是则说明点击了edit，如果不是则说明没有点击

        return editable ? (

          <span>
            <Typography.Link onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </Typography.Link>
            <Popconfirm title="确定取消吗?" onConfirm={cancel}>
              <a>取消</a>
            </Popconfirm>
          </span>

        ) : (
          //点击了edit就把这一行的key设为editingKey，重新渲染，然后editable变为true，显示保存和取消a标签，editingKey不等于空说明有行点了edit，则其他行都是disabled
          <Space size="middle">
            <Typography.Link disabled={editingKey !== '' || loginstate.role.loginname === "admin"} onClick={() => edit(record)}>
              编辑
            </Typography.Link>

            <Popconfirm title="确定删除吗?" onConfirm={() => deldata(record.key)} onCancel={cancel} okText="Yes" cancelText="No">
              <a disabled={loginstate.role.loginname === "admin"}>
                删除
              </a>
            </Popconfirm>
          </Space>
        );

      },
    },
  ];

  const columnsformileagecheck = [
    {
      title: '计算里程',
      dataIndex: 'calmileage',
      key: 'calmileage',
    },
    {
      title: 'ODO里程',
      dataIndex: 'odo',
      key: 'odo',
    },
    {
      title: '误差',
      dataIndex: 'difference',
      key: 'difference',
    },
    {
      title: '信息',
      dataIndex: 'info',
      key: 'info',
    },
  ];

  //添加表单的添加方法
  const onAddDate = async (values) => {

    setOpen(false);
    values.loginname = loginstate.role.loginname;
    const r = await addtrigger(values);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(r.error.data);

    } else {
      messageerror(r.error.data);
    }

  };
  const save = async (key) => {
    //这里的row就是表单的所有项的值作为一个row对象存储
    //这里会异步
    const row = await form.validateFields();

    row.key = key;
    row.loginname = loginstate.role.loginname;

    //发送put请求到服务器
    const r = await edittrigger(row);
    //console.log(r);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(r.error.data);

    } else {
      messageerror(r.error.data);
    }
    setEditingKey('');
    setSelectedRowKeys([]); // 清除表格选择
    setparaisselected(false);//保存时让button不起作用
  };

  const cancel = () => { // 定义 cancel 函数以重置 editingKey state
    setEditingKey('');

  };
  const deldata = async (key) => { // 定义 cancel 函数以重置 editingKey state
    //console.log(key);
    const r = await deltrigger(key);
    if (r.error.originalStatus === 200) {
      //console.log("成功")
      messagesucess(r.error.data);

    } else {
      messageerror(r.error.data);
    }
    setEditingKey('');

  };
  const handleTableChange = (pagination, filters, sorter) => {

    setTableParams({
      pagination,
      //filters,
      // ...sorter,
    });

    // pagination分页异常值如果和tableParams里的分页异常值不一样，就把异常值清零，重新发送请求
    // if (pagination.pageSize !== tableParams.pagination?.pageSize) {
    //   setData([]);
    // }
  };
  //这个比EditableCell先执行，这个是点了edit后展示的form表单的设置
  const mergedColumns = columns.map((col) => { // 通过映射 columns 数组定义 mergedColumns 数组
    if (!col.editable) { // 如果列不可编辑，返回列
      return col;
    }

    return {
      ...col, // 否则返回编辑行新对象，其 render 函数为 EditableCell 组件
      onCell: (record) => (

        {

          record,
          //inputType: col.dataIndex === 'category' ? 'radio' : 'text',
          dataIndex: col.dataIndex,
          title: col.title,
          editing: isEditing(record),//判断这一行的key是否为editingKey，为true说明这一行点击了edit
          // 将单元格的原始值传递给 EditableCell 组件

        }),
    };
  });

  //一旦tableParams发生改变，就调用此方法，当然第一次加载页面的时候也会调用此方法，所以第一次总是会去发送请求
  //useEffect 钩子函数将在组件渲染后执行 
  useEffect(() => {
    //如果请求成功则调用setTableParams方法

    if (result.isSuccess) {
      //console.log(result.data.pagedata);
      setTableParams({
        ...tableParams,
        pagination: {
          ...tableParams.pagination,
          total: result.data.total,

        },
      });
    }

  }, [result.isSuccess]);

  // useEffect(() => {
  //   console.log(badgestatus);

  // }, [badgestatus]);


  return (
    <>
      {/* 必须把contextHolder包裹整个组件才能显示message消息框 */}
      {contextHolder}
      <Button
        onClick={() => {
          setOpen(true);
        }}
        type="primary"
        disabled={loginstate.role.loginname === "admin"}
        //如果是admin登陆的就不需要执行添加特定用户参数
        //disabled={loginstate.role.loginname === "admin"}
        style={{
          marginBottom: 16,
        }}
      // disabled={loginstate.role==="admin"?false:true}
      >
        添加
      </Button>
      <CollectionCreateForm
        open={open}
        onCreate={onAddDate}

        onCancel={() => {
          setOpen(false);
        }}
      />
      <Form form={form} component={false}>

        <Table
          components={{
            body: {
              cell: EditableCell, // 使用 EditableCell 组件作为表格单元格
            },
          }}
          bordered
          rowHeight={100}
          rowSelection={rowSelection}
          dataSource={result.isSuccess ? result.data.pagedata : []} // 将 dataSource prop 设置为异常值 state
          columns={mergedColumns} // 将 columns prop 设置为 mergedColumns 数组
          rowClassName="editable-row"
          pagination={tableParams.pagination}
          loading={result.isLoading}
          onChange={handleTableChange}
          scroll={{ x: 'max-content' }}
        />
        <Form.Item name="range-picker" label="选择日期范围（不要跨年）">
          <DatePicker.RangePicker
            status="error"
            style={{
              width: '100%',
            }}
            onChange={dateselect}
          />
        </Form.Item>

        <Form.Item>
          {!loading ? (<Popover content={popovercontent} title="里程校验">
            <Button
              block type="primary"
              size="large"

              disabled={!paraisselected || loginstate.role.loginname === "admin" || !dateselected}
              onClick={mileagecheckexcute}
            >里程校验</Button>
          </Popover>) :
            (<Spin tip="里程校验中……请不要切换页面！！！" size="large">
              <div className="content" />
            </Spin>)}
        </Form.Item>

      </Form>
      <Modal title="导入结果信息" open={isModalOpen} onOk={handleOk} onCancel={handleCancel} footer={null}>
        <Table
          columns={columnsformileagecheck}
          dataSource={Modalinfo}
          rowKey={(record) => record.key}
        />
      </Modal>

    </>
  )
}

export default DataMileageCheckProp